'''
Created on Mar 31, 2012

@author: e911miri
'''

import cherrypy
from jinja2 import Environment, FileSystemLoader
from helper import cachecombo
from resultModel import result, getresult

env = Environment(loader=FileSystemLoader('templates'))

class Root:
    @cherrypy.expose
    @cherrypy.tools.allow(methods=['GET'])
    def index(self):
        if cherrypy.request.cache['data']:            
            testnum = cherrypy.request.cache['regnum']
            testpin = cherrypy.request.cache['pin']
            r = {'regnum': testnum, 'pin': testpin}
        else:
            r = getresult()
            if r:
                cherrypy.request.cache['data'] = True
                cherrypy.request.cache['regnum'] = r['regnum']
                cherrypy.request.cache['pin'] = r['pin']
            else: r = {'error':'No values in the database'}
        tmpl = env.get_template('index.html')
        return tmpl.render(r)
    
    @cherrypy.expose
    @cherrypy.tools.allow(methods=['POST', 'GET'])
    def result(self, reg_num=None, year=None, pin=None):
        if reg_num and pin:
            r = result(reg_num=reg_num, pin=pin)
            try:               
                cnum = 'c' + str(r['combo'])
                try:
                    c = cherrypy.request.cache[cnum]
                except KeyError:
                    cherrypy.request.cache[cnum] = cachecombo(r['combo'])
                    c = cherrypy.request.cache[cnum]
                print(cachecombo(r['combo']))
                r['duo'] = list(zip(r['score'], c))
            except KeyError:
                pass              
        else:
            raise cherrypy.HTTPRedirect('/')
        tmpl = env.get_template('resultpage.html')        
        return tmpl.render(r)

def defaulterror(status, message, traceback, version):
    return "An Error has occurred"
